package com.itlong.cloud.operate.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.operate.OperateRoleGetPageDTO;
import com.itlong.cloud.POJO.PO.OperateRolePO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.AssessSyncDataTypeEnum;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.operate.dao.IOperateAssessFunctionDao;
import com.itlong.cloud.operate.dao.IOperateFunctionDao;
import com.itlong.cloud.operate.dao.IOperateRoleDao;
import com.itlong.cloud.operate.service.IOperateRoleService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      角色信息业务接口实现类
 * </desc>
 *
 * @createDate 2017/09/25
 */
@Service
public class OperateRoleServiceImpl implements IOperateRoleService{

    @Autowired
    private IOperateRoleDao iOperateRoleDao;

    @Autowired
    private IOperateFunctionDao iOperateFunctionDao;

    @Autowired
    private IOperateAssessFunctionDao iOperateAssessFunctionDao;

    @Autowired
    MessageSender messageSender;
    /**
     * <desc>
     *      保存角色
     * </desc>
     *
     * @param operateRolePO 角色实体
     * @return sql执行行数
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer save(OperateRolePO operateRolePO) throws Exception {
        operateRolePO.setRoleId(LogicIdUtil.bussinessId());
        operateRolePO.setCreateTime(new Date());
        JSONObject jsonObject = new JSONObject();
        operateRolePO.setSyncType(1);
        jsonObject.put("data",operateRolePO);
        jsonObject.put("type", AssessSyncDataTypeEnum.ROLE.getType());
        messageSender.send(RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_QUEUE, jsonObject.toJSONString(),
                RabbitMQConstant.RABBITMQ_SYNC_DATA_EXCHANGE, RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_KEY);
        return iOperateRoleDao.save(SqlUtil.durableData(operateRolePO, PlatformConstants.TABLE_SAVE));
    }


    /**
     * <desc>
     *      更新角色
     * </desc>
     *
     * @param operateRolePO 资源角色实体
     * @return sql执行行数
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer update(OperateRolePO operateRolePO) throws Exception {
        OperateRolePO oldPo=iOperateRoleDao.getOne(operateRolePO);
        if(!oldPo.getRoleName().equals(operateRolePO.getRoleName())){
            //如果等于老角色的名称直接更新，否则检查是否已存在角色名
            if(iOperateRoleDao.checkRoleNameExist(operateRolePO.getRoleName()) > 0){
                return -1;
            }
        }
        operateRolePO.setUpdateTime(new Date());
        JSONObject jsonObject = new JSONObject();
        operateRolePO.setSyncType(2);
        jsonObject.put("data",operateRolePO);
        jsonObject.put("type", AssessSyncDataTypeEnum.ROLE.getType());
        messageSender.send(RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_QUEUE, jsonObject.toJSONString(),
                RabbitMQConstant.RABBITMQ_SYNC_DATA_EXCHANGE, RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_KEY);
        return iOperateRoleDao.update(SqlUtil.durableData(operateRolePO, PlatformConstants.TABLE_UPDATE));
    }

    /**
     * <desc>
     *      通过id获取角色
     * </desc>
     *
     * @param operateRolePO 角色实体
     * @return 角色实体
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public OperateRolePO getOne(OperateRolePO operateRolePO) {
        return iOperateRoleDao.getOne(operateRolePO);
    }

    /**
     * <desc>
     *      获取所有角色
     * </desc>
     *
     * @return 资源实体集合
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public List<OperateRolePO> getList(String userId) {
        return iOperateRoleDao.getListByUser(userId);
    }



    /**
     * <desc>
     *      获取分页数据
     * </desc>
     *
     * @param pageDTO 查询参数DTO
     * @return page模型
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Page<OperateRolePO> getPage(OperateRoleGetPageDTO pageDTO) throws Exception {
        //将DTO转换为Map params
        Map<String, Object> params = SqlUtil.convertBeanToMapParams(pageDTO);
        //分页类默认pageSize为20
        Page<OperateRolePO> page = new Page<>();
        page.getPage().setPageSize(pageDTO.getPageSize());
        page.getPage().setCurrentPage(pageDTO.getCurrentPage());
        params.put("currentPage",page.getPage().getStartSlip());
        params.put("pageSize",page.getPage().getPageSize());
        //填充返回数据集
        page.setRows(iOperateRoleDao.getPageList(params), iOperateRoleDao.getPageCount(params));
        return page;
    }

    /**
     * <desc>
     *      删除角色
     * </desc>
     *
     * @param roleIds 角色id数组
     * @return sql执行行数
     * @author Jiaqi.X
     * @createDate 2017/09/25
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer delete(String roleIds) throws Exception {
        String roleId[] = StringHandlerUtil.splitString(roleIds);
        JSONObject jsonObject = new JSONObject();
        OperateRolePO operateRolePO = new OperateRolePO();
        operateRolePO.setSyncType(3);
        operateRolePO.setDeleteSyncRoleIds(roleIds);
        jsonObject.put("data",operateRolePO);
        jsonObject.put("type", AssessSyncDataTypeEnum.ROLE.getType());
        messageSender.send(RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_QUEUE, jsonObject.toJSONString(),
                RabbitMQConstant.RABBITMQ_SYNC_DATA_EXCHANGE, RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_KEY);
        return iOperateRoleDao.delete(roleId,new Date());
    }

    /**
     * <desc>
     *      保存角色菜单资源
     * </desc>
     *
     * @param roleId 角色id
     * @param functionIds 资源id 多个,号分隔
     * @return
     * @author Jiaqi.X
     * @version 1.0
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveRoleFunction(String roleId, String functionIds,String assessFunctionIds, String myUserName) throws Exception {
        //删除之前的角色菜单 物理删除
        iOperateFunctionDao.deleteRoleFunctions(roleId);
        //删除之前的报价菜单
        iOperateAssessFunctionDao.deleteRoleFunctions(roleId);
        //保存报价菜单
        Date nowTime = new Date();
        if (StringUtils.isNotBlank(roleId)){
            String[] functions = StringHandlerUtil.splitString(assessFunctionIds);
            Map<String, Object> param = new HashMap<>();
            param.put("roleId", roleId);
            param.put("createTime", nowTime);
            param.put("updateTime", nowTime);
            param.put("createUserId",myUserName);
            param.put("operateUserId",myUserName);
            param.put("status", DataStatusEnum.NORMAL.getType());
            param.put("type",1);
            param.put("functionIds", functions.length > 0 ? functions : null);
            if(functions.length > 0) {
                iOperateAssessFunctionDao.saveRoleFunction(param);
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",param);
            jsonObject.put("type", AssessSyncDataTypeEnum.ROLEFUNCTION.getType());
            messageSender.send(RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_QUEUE, jsonObject.toJSONString(),
                    RabbitMQConstant.RABBITMQ_SYNC_DATA_EXCHANGE, RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_KEY);
        }
        //保存运营菜单
        if(functionIds !=null && !functionIds.isEmpty()) {
            Map<String, Object> param = new HashMap<>();
            param.put("roleId", roleId);
            param.put("functionIds", StringHandlerUtil.splitString(functionIds));
            param.put("createTime", nowTime);
            param.put("status", DataStatusEnum.NORMAL.getType());
            return iOperateRoleDao.saveRoleFunction(param);
        }else{
            return 1;
        }
    }


    /**
     * <desc>
     *       为角色分配人员
     * </desc>
     *
     * @param roleId    角色id
     * @param allotUsers    需要分配的人员id 多个，号分隔
     * @param userIds 当前列表所有人员id 多个，号分隔
     * @return sql执行行数
     * @author Jiaqi.X
     * @createDate 2017/10/10
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer saveRoleUsers(String roleId,String allotUsers,String userIds) throws Exception {
        //防止绕过前端提交，工程人员不可编辑
        if(roleId!=null&&!roleId.equals("1")) {
            //先将用户的角色删除 物理删除
            iOperateRoleDao.deleteRoleUsers(StringHandlerUtil.splitString(userIds), roleId);
            //为用户分配角色
            if(StringUtils.isBlank(allotUsers)) {
                return 1;
            }
            Map<String, Object> params = new HashMap<>();
            params.put("allotUsers", StringHandlerUtil.splitString(allotUsers));
            params.put("roleId", roleId);
            params.put("status", DataStatusEnum.NORMAL.getType());
            params.put("createTime", new Date());
            params.put("userIds",userIds);
            params.put("type",2);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",params);
            jsonObject.put("type", AssessSyncDataTypeEnum.ROLEFUNCTION.getType());
            messageSender.send(RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_QUEUE, jsonObject.toJSONString(),
                    RabbitMQConstant.RABBITMQ_SYNC_DATA_EXCHANGE, RabbitMQConstant.RABBITMQ_ASSESS_SYNC_DATA_KEY);
            return iOperateRoleDao.saveRoleUsers(params);
        }
        return 1;
    }

    /**
     * <desc>
     *      查询角色名是否已存在
     * </desc>
     *
     * @param roleName 角色名称
     * @return
     * @author Jiaqi.X
     * @createDate 2017/12/25
     */
    @Override
    public Integer checkRoleNameExist(String roleName) {
        return iOperateRoleDao.checkRoleNameExist(roleName);
    }


}
